<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 公共辅助函数库
 * ============================================================================
 * codeDescription
 * ============================================================================
 * @author selenium <578288126@qq.com>
 * @copyright Copyright (c) 2011 - 2012, mei.com.cn.
 * @version 1.0
 * @date 2012-8-1
 * @name common_helper.php
 *
 */
if ( ! function_exists('ip'))
{

	function getIP() {
		$IP1= $_SERVER['REMOTE_ADDR'];        // Obtains the IP address
		$computerName = gethostbyaddr($IP1);

		if (getenv("HTTP_CLIENT_IP"))
		$ip = getenv("HTTP_CLIENT_IP");
		else if(getenv("HTTP_X_FORWARDED_FOR"))
		$ip = getenv("HTTP_X_FORWARDED_FOR");
		else if(getenv("REMOTE_ADDR"))
		$ip = getenv("REMOTE_ADDR");
		else
		$ip = "UNKNOWN";

		if ($ip=="127.0.0.1"){
			$myIP = gethostbyname(trim(`hostname`));
		}else{
			$myIP=$ip;;
		}
		return $myIP;
	}

	/**
	 * 获取请求ip
	 *
	 * @return ip地址
	 */
	function ip() {
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$ip = getenv('REMOTE_ADDR');
		} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
	}
}
if ( ! function_exists('toDate'))
{
	function toDate($time, $format = 'Y-m-d H:i:s') {
		if (empty ( $time )) {
			return '';
		}
		$format = str_replace ( '#', ':', $format );
		return date ($format, $time );
	}
}
if ( ! function_exists('back_error'))
{
	function back_error($msg)
	{
		echo "<script type =\"text/javascript\">alert('{$msg}');history.go(-1);</script>";
		exit;
	}
}
if ( ! function_exists('go_success'))
{
	function go_success($msg,$href)
	{
		echo "<script type =\"text/javascript\">alert('{$msg}');location.href='{$href}';</script>";
		exit;
	}
}
if ( ! function_exists('tosDate'))
{
	function tosDate($time, $format = 'Y-m-d') {
		if (empty ( $time )) {
			return '';
		}
		$format = str_replace ( '#', ':', $format );
		return date ($format, $time );
	}
}
if ( ! function_exists('new_addslashes'))
{
	/**
	 * 返回经addslashes处理过的字符串或数组
	 * @param $string 需要处理的字符串或数组
	 * @return mixed
	 */
	function new_addslashes($string){
		if(!is_array($string)) return addslashes($string);
		foreach($string as $key => $val) $string[$key] = new_addslashes($val);
		return $string;
	}
}
if ( ! function_exists('new_stripslashes'))
{
	/**
	 * 返回经stripslashes处理过的字符串或数组
	 * @param $string 需要处理的字符串或数组
	 * @return mixed
	 */
	function new_stripslashes($string) {
		if(!is_array($string)) return stripslashes($string);
		foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
		return $string;
	}
}
if ( ! function_exists('new_html_special_chars'))
{
	/**
	 * 返回经htmlspecialchars处理过的字符串或数组
	 * @param $obj 需要处理的字符串或数组
	 * @return mixed
	 */
	function new_html_special_chars($string) {
		if(!is_array($string)) return htmlspecialchars($string);
		foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
		return $string;
	}
}
if ( ! function_exists('safe_replace'))
{
	/**
	 * 安全过滤函数
	 *
	 * @param $string
	 * @return string
	 */
	function safe_replace($string) {
		$string = str_replace('%20','',$string);
		$string = str_replace('%27','',$string);
		$string = str_replace('%2527','',$string);
		$string = str_replace('*','',$string);
		$string = str_replace('"','&quot;',$string);
		$string = str_replace("'",'',$string);
		$string = str_replace('"','',$string);
		$string = str_replace(';','',$string);
		$string = str_replace('<','&lt;',$string);
		$string = str_replace('>','&gt;',$string);
		$string = str_replace("{",'',$string);
		$string = str_replace('}','',$string);
		$string = str_replace('\\','',$string);
		return $string;
	}
}
if ( ! function_exists('trim_unsafe_control_chars'))
{
	/**
	 * 过滤ASCII码从0-28的控制字符
	 * @return String
	 */
	function trim_unsafe_control_chars($str) {
		$rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
		return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
	}
}
if ( ! function_exists('trim_textarea'))
{
	/**
	 * 格式化文本域内容
	 *
	 * @param $string 文本域内容
	 * @return string
	 */
	function trim_textarea($string) {
		$string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );
		return $string;
	}
}
//11111
if ( ! function_exists('format_js'))
{
	/**
	 * 将文本格式成适合js输出的字符串
	 * @param string $string 需要处理的字符串
	 * @param intval $isjs 是否执行字符串格式化，默认为执行
	 * @return string 处理后的字符串
	 */
	function format_js($string, $isjs = 1) {
		$string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
		return $isjs ? 'document.write("'.$string.'");' : $string;
	}
}
if ( ! function_exists('trim_script'))
{
	/**
	 * 转义 javascript 代码标记
	 *
	 * @param $str
	 * @return mixed
	 */
	function trim_script($str) {
		if(is_array($str)){
			foreach ($str as $key => $val){
				$str[$key] = trim_script($val);
			}
		}else{
			$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
			$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
			$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
			$str = preg_replace ( '/]]\>/si', ']] >', $str );
		}
		return $str;
	}
}
if ( ! function_exists('get_url'))
{
	/**
	 * 获取当前页面完整URL地址
	 */
	function get_url() {
		$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
		$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
		$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
		$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
		return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
	}
}
if ( ! function_exists('str_cut'))
{
	/**
	 * 字符截取 支持UTF8/GBK
	 * @param $string
	 * @param $length
	 * @param $dot
	 */
	function str_cut($string, $length, $dot = '...') {
		$strlen = strlen($string);
		if($strlen <= $length) return $string;
		$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
		$strcut = '';
		if(strtolower(APP_CHARSET) == 'utf-8') {
			$length = intval($length-strlen($dot)-$length/3);
			$n = $tn = $noc = 0;
			while($n < strlen($string)) {
				$t = ord($string[$n]);
				if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$tn = 1; $n++; $noc++;
				} elseif(194 <= $t && $t <= 223) {
					$tn = 2; $n += 2; $noc += 2;
				} elseif(224 <= $t && $t <= 239) {
					$tn = 3; $n += 3; $noc += 2;
				} elseif(240 <= $t && $t <= 247) {
					$tn = 4; $n += 4; $noc += 2;
				} elseif(248 <= $t && $t <= 251) {
					$tn = 5; $n += 5; $noc += 2;
				} elseif($t == 252 || $t == 253) {
					$tn = 6; $n += 6; $noc += 2;
				} else {
					$n++;
				}
				if($noc >= $length) {
					break;
				}
			}
			if($noc > $length) {
				$n -= $tn;
			}
			$strcut = substr($string, 0, $n);
			$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
		} else {
			$dotlen = strlen($dot);
			$maxi = $length - $dotlen - 1;
			$current_str = '';
			$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
			$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
			$search_flip = array_flip($search_arr);
			for ($i = 0; $i < $maxi; $i++) {
				$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
				if (in_array($current_str, $search_arr)) {
					$key = $search_flip[$current_str];
					$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
				}
				$strcut .= $current_str;
			}
		}
		return $strcut.$dot;
	}
}
if ( ! function_exists('timeAgo'))
{
	function  timeAgo($timestamp, $granularity=2, $format='Y-m-d H:i:s'){
		$difference = time() - $timestamp;
		if($difference < 0) return '0 seconds ago';
		elseif($difference < 864000){
			$periods = array('周' => 604800,'天' => 86400,'小时' => 3600,'分' => 60,'秒' => 1);
			$output = '';
			foreach($periods as $key => $value){
				if($difference >= $value){
					$time = round($difference / $value);
					$difference %= $value;
					$output .= ($output ? ' ' : '').$time.' ';
					$output .= $key;
					$granularity--;
				}
				if($granularity == 0) break;
			}
			return ($output ? $output : '0 秒').' 之前';
		}
		else return date($format, $timestamp);
	}
}
if ( ! function_exists('create_f'))
{
	function create_f($directory,$file,$data,$flags=FILE_USE_INCLUDE_PATH)
	{
		$all_file =  FCPATH.'data'.DIRECTORY_SEPARATOR.$directory;
		if (!file_exists($all_file)) {

			@dir_create($all_file);
		}
		if(is_array($data))
		{
			//要写入PHP文件的数组
			$string_start = "<?php\n return ";
			$string_process = var_export($data, TRUE);
			$string_end = "\n?>";
			$string = $string_start.$string_process.$string_end;
		}
		else
		{
			$string	=	$data;
		}
		file_put_contents(FCPATH.'data'.DIRECTORY_SEPARATOR.$directory.DIRECTORY_SEPARATOR.$file,$string,$flags);
	}
}


if ( ! function_exists('create_config_f'))
{
	function create_config_f($directory,$file,$data,$type,$flags=FILE_USE_INCLUDE_PATH)
	{
		$all_file =  FCPATH.'data'.DIRECTORY_SEPARATOR.$directory;
		if (!file_exists($all_file)) {

			@dir_create($all_file);
		}
		if(is_array($data))
		{
			//要写入PHP文件的数组
			$string_start = "<?php\n $".$type."=";
			$string_process = var_export($data, TRUE);
			$string_end = "; \n return $".$type.";\n?>";
			$string = $string_start.$string_process.$string_end;
		}
		else
		{
			$string	=	$data;
		}
		file_put_contents(FCPATH.'data'.DIRECTORY_SEPARATOR.$directory.DIRECTORY_SEPARATOR.$file,$string,$flags);
	}
}


if ( ! function_exists('create_f_font'))
{
	function create_f_font($directory,$file,$data,$flags=FILE_USE_INCLUDE_PATH)
	{
		$all_file =  FONT_PATH.'data'.DIRECTORY_SEPARATOR.$directory;
		if (!file_exists($all_file)) {

			@dir_create($all_file);
		}
		if(is_array($data))
		{
			//要写入PHP文件的数组
			$string_start = "<?php\n return ";
			$string_process = var_export($data, TRUE);
			$string_end = "\n?>";
			$string = $string_start.$string_process.$string_end;
		}
		else
		{
			$string	=	$data;
		}
		file_put_contents(FONT_PATH.'data'.DIRECTORY_SEPARATOR.$directory.DIRECTORY_SEPARATOR.$file,$string,$flags);
	}
}
if ( ! function_exists('read_f'))
{
	function read_f($directory,$file)
	{
		$all_file = FCPATH.'data'.DIRECTORY_SEPARATOR.$directory.DIRECTORY_SEPARATOR.$file;
		if (!file_exists($all_file)) {
			return array ();
		}
		$r = include $all_file;
		return  $r;
	}
}

if(! function_exists('del_f')){

	function del_f($directory,$file)
	{
		$all_file = FCPATH.'data'.DIRECTORY_SEPARATOR.$directory.DIRECTORY_SEPARATOR.$file;
		if (!file_exists($all_file)){

			echo '文件不存在';
			exit();
		}
		unlink($all_file);
	}
}



if ( ! function_exists('SendGET'))
{
	function SendGET($mess,$mobile){
		$message=@iconv('utf-8','gbk',$mess);//发送get请求，一定要转成gbk的数据，可以使用iconv('utf-8','gbk','测试')这样转
		$_url="http://sms.ccme.cc:80/send.jsp?circle=meizhi&pwd=meizhisms&mobile={$mobile}&service=73c6809b-5e85-4d1a-abea-4ee5ee56f900&msgid=3952567&message=".$message;
		$url = parse_url($_url);
		$contents = '';
		$fp = fsockopen($url['host'],$url['port']);
		if($fp){
			$_request = $url['path'].($url['query']==''?'':'?'.$url['query']);
			fputs($fp,'GET '.$_request." HTTP/1.0\r\n");
			fputs($fp,"Host: ".$url['host']."\n");
			fputs($fp,"Content-type: application/x-www-form-urlencoded\n");
			fputs($fp,"Connection: close\n\n");
			$line = fgets($fp,1024);
			if(!preg_match_all( '/HTTP\/1\.\d (\d{3}) ([\w\d\s+]+)/', $line, $matches))
			return;
			else{
				$results = '';
				$contents = '';
				$inheader = 1;
				while(!feof($fp)){
					$line = fgets($fp,2048);
					if($inheader&&($line == "\n" || $line == "\r\n")){
						$inheader = 0;
					}elseif(!$inheader){
						$contents .= $line;
					}
				}
				fclose($fp);
			}
		}
		return $contents;
	}
}
if ( ! function_exists('socketGet'))
{
	function socketGet($url,$data){
		$encoded = "";
		while (list($k,$v) = each($data)) {
			$encoded .= ($encoded ? "&" : "");
			$encoded .= rawurlencode($k)."=".rawurlencode($v);
		}
		$_url=$url.'?'.$encoded;
		$url = parse_url($_url);
		if (!$url) return "couldn't parse url";
		if (!isset($url['port'])) { $url['port'] = ""; }
		if (!isset($url['query'])) { $url['query'] = ""; }
		$contents = '';
		$fp = fsockopen($url['host'],$url['port'] ? $url['port'] : 80);
		if($fp){
			$_request = $url['path'].($url['query']==''?'':'?'.$url['query']);
			fputs($fp,'GET '.$_request." HTTP/1.0\r\n");
			fputs($fp,"Host: ".$url['host']."\n");
			fputs($fp,"Content-type: application/x-www-form-urlencoded\n");
			fputs($fp,"Connection: close\n\n");
			$line = fgets($fp,1024);
			if(!preg_match_all( '/HTTP\/1\.\d (\d{3}) ([\w\d\s+]+)/', $line, $matches))
			return;
			else{
				$results = '';
				$contents = '';
				$inheader = 1;
				while(!feof($fp)){
					$line = fgets($fp,2048);
					if($inheader&&($line == "\n" || $line == "\r\n")){
						$inheader = 0;
					}elseif(!$inheader){
						$contents .= $line;
					}
				}
				fclose($fp);
			}
		}
		return $contents;
	}
}
if ( ! function_exists('socketPost'))
{
	function socketPost($url, $data)
	{
		$url = parse_url($url);
		if (!$url) return "couldn't parse url";
		if (!isset($url['port'])) { $url['port'] = ""; }
		if (!isset($url['query'])) { $url['query'] = ""; }
		$encoded = "";
		while (list($k,$v) = each($data)) {
			$encoded .= ($encoded ? "&" : "");
			$encoded .= rawurlencode($k)."=".rawurlencode($v);
		}
		$fp = fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
		if (!$fp) return "Failed to open socket to $url[host]";

		fputs($fp, sprintf("POST %s%s%s HTTP/1.0\n", $url['path'], $url['query'] ? "?" : "", $url['query']));
		fputs($fp, "Host: $url[host]\n");
		fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
		fputs($fp, "Content-length: " . strlen($encoded) . "\n");
		fputs($fp, "Connection: close\n\n");

		fputs($fp, "$encoded\n");

		$line = fgets($fp,1024);
		if (!preg_match("/HTTP\/1\.\d (\d{3}) ([\w\d\s+]+)/", $line)) return;

		$results = ""; $inheader = 1;
		while(!feof($fp)) {
			$line = fgets($fp,1024);
			if ($inheader && ($line == "\n" || $line == "\r\n")) {
				$inheader = 0;
			}
			elseif (!$inheader) {
				$results .= $line;
			}
		}
		fclose($fp);
		return $results;
	}
}
if ( ! function_exists('returnSquarePoint'))
{
	/**
	 *计算某个经纬度的周围某段距离的正方形的四个点
	 *
	 *@param lng float 经度
	 *@param lat float 纬度
	 *@param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为0.5千米
	 *@return array 正方形的四个点的经纬度坐标
	 */
	function returnSquarePoint($lng, $lat,$distance = 10){

		$dlng =  2 * asin(sin($distance / (2 * EARTH_RADIUS)) / cos(deg2rad($lat)));
		$dlng = rad2deg($dlng);

		$dlat = $distance/EARTH_RADIUS;
		$dlat = rad2deg($dlat);

		return array(
				'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
				'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
				'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
				'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
		);
	}
}
if ( ! function_exists('get_dist'))
{
	/**
	 * 根据半正失公式，获取两地理坐标之间的距离
	 *
	 * @param integer 坐标1经度
	 * @param integer 坐标1纬度
	 * @param integer 坐标2经度
	 * @param integer 坐标2纬度
	 * @return integer 两坐标之间的距离，以KM为单位
	 */
	function get_dist($lng1, $lat1, $lng2 ,$lat2)
	{
		$r = 6371.137;
		$dlat = deg2rad($lat2 - $lat1);
		$dlng = deg2rad($lng2 - $lng1);
			
		$a = pow(sin($dlat / 2), 2) +
		cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
		pow(sin($dlng / 2), 2);

		$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
			
		return $r * $c;
	}
}
if ( ! function_exists('get_sysinfo'))
{
	/**
	 * 获取系统信息
	 */
	function get_sysinfo() {
		$sys_info['os']             = PHP_OS;
		$sys_info['zlib']           = function_exists('gzclose');//zlib
		$sys_info['safe_mode']      = (boolean) ini_get('safe_mode');//safe_mode = Off
		$sys_info['safe_mode_gid']  = (boolean) ini_get('safe_mode_gid');//safe_mode_gid = Off
		$sys_info['timezone']       = function_exists("date_default_timezone_get") ? date_default_timezone_get() : L('no_setting');
		$sys_info['socket']         = function_exists('fsockopen') ;
		$sys_info['curl']           = function_exists('curl_init');
		$sys_info['web_server']     = $_SERVER['SERVER_SOFTWARE'];
		$sys_info['phpv']           = phpversion();
		$sys_info['fileupload']     = @ini_get('file_uploads') ? ini_get('upload_max_filesize') :'unknown';
		$sys_info['mysqlv']         = mysql_get_server_info();
		return $sys_info;
	}
}
if ( ! function_exists('file_down'))
{
	/**
	 * 文件下载
	 * @param $filepath 文件路径
	 * @param $filename 文件名称
	 */

	function file_down($filepath, $filename = '') {
		if(!$filename) $filename = basename($filepath);
		if(is_ie()) $filename = rawurlencode($filename);
		$filetype = fileext($filename);
		$filesize = sprintf("%u", filesize($filepath));
		if(ob_get_length() !== false) @ob_end_clean();
		header('Pragma: public');
		header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header('Cache-Control: pre-check=0, post-check=0, max-age=0');
		header('Content-Transfer-Encoding: binary');
		header('Content-Encoding: none');
		header('Content-type: '.$filetype);
		header('Content-Disposition: attachment; filename="'.$filename.'"');
		header('Content-length: '.$filesize);
		readfile($filepath);
		exit;
	}
}
if ( ! function_exists('is_ie'))
{
	/**
	 * IE浏览器判断
	 */
	function is_ie() {
		$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
		if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
		if(strpos($useragent, 'msie ') !== false) return true;
		return false;
	}
}
if ( ! function_exists('fileext'))
{
	/**
	 * 取得文件扩展
	 *
	 * @param $filename 文件名
	 * @return 扩展名
	 */
	function fileext($filename) {
		return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
	}
}
if ( ! function_exists('random'))
{
	/**
	 * 产生随机字符串
	 *
	 * @param    int        $length  输出长度
	 * @param    string     $chars   可选的 ，默认为 0123456789
	 * @return   string     字符串
	 */
	function random($length, $chars = '0123456789') {
		$hash = '';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
		return $hash;
	}
}
if ( ! function_exists('randstr'))
{
	/**
	 * 产生随机字符串
	 *
	 * 产生一个指定长度的随机字符串,并返回给用户
	 *
	 * @access public
	 * @param int $len 产生字符串的位数
	 * @return string
	 */
	function randstr($len=6) {
		$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		// characters to build the password from
		mt_srand((double)microtime()*1000000*getmypid());
		// seed the random number generater (must be done)
		$password='';
		while(strlen($password)<$len)
		$password.=substr($chars,(mt_rand()%strlen($chars)),1);
		return $password;
	}
}
if ( ! function_exists('string2array'))
{
	/**
	 * 将字符串转换为数组
	 *
	 * @param	string	$data	字符串
	 * @return	array	返回数组格式，如果，data为空，则返回空数组
	 */
	function string2array($data) {
		if($data == '') return array();
		@eval("\$array = $data;");
		return $array;
	}
}
if ( ! function_exists('array2string'))
{
	/**
	 * 将数组转换为字符串
	 *
	 * @param	array	$data		数组
	 * @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
	 * @return	string	返回字符串，如果，data为空，则返回空
	 */
	function array2string($data, $isformdata = 1) {
		if($data == '') return '';
		if($isformdata) $data = new_stripslashes($data);
		return addslashes(var_export($data, TRUE));
	}
}
if ( ! function_exists('sizecount'))
{
	/**
	 * 转换字节数为其他单位
	 *
	 *
	 * @param	string	$filesize	字节大小
	 * @return	string	返回大小
	 */
	function sizecount($filesize) {
		if ($filesize >= 1073741824) {
			$filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
		} elseif ($filesize >= 1048576) {
			$filesize = round($filesize / 1048576 * 100) / 100 .' MB';
		} elseif($filesize >= 1024) {
			$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
		} else {
			$filesize = $filesize.' Bytes';
		}
		return $filesize;
	}
}
if ( ! function_exists('sys_auth'))
{
	/**
	 * 字符串加密、解密函数
	 *
	 *
	 * @param	string	$txt		字符串
	 * @param	string	$operation	ENCODE为加密，DECODE为解密，可选参数，默认为ENCODE，
	 * @param	string	$key		密钥：数字、字母、下划线
	 * @param	string	$expiry		过期时间
	 * @return	string
	 */
	function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
		$key_length = 4;
		$key = md5($key != '' ? $key : AUTH_KEY);
		$fixedkey = md5($key);
		$egiskeys = md5(substr($fixedkey, 16, 16));
		$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
		$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
		$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));

		$i = 0; $result = '';
		$string_length = strlen($string);
		for ($i = 0; $i < $string_length; $i++){
			$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
		}
		if($operation == 'ENCODE') {
			return $runtokey . str_replace('=', '', base64_encode($result));
		} else {
			if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
				return substr($result, 26);
			} else {
				return '';
			}
		}
	}
}
if ( ! function_exists('is_email'))
{
	/**
	 * 判断email格式是否正确
	 * @param $email
	 */
	function is_email($email) {
		return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
	}
}
/**
 * iconv 编辑转换
 */
if (!function_exists('iconv')) {
	function iconv($in_charset, $out_charset, $str) {
		$in_charset = strtoupper($in_charset);
		$out_charset = strtoupper($out_charset);
		if (function_exists('mb_convert_encoding')) {
			return mb_convert_encoding($str, $out_charset, $in_charset);
		} else {
			pc_base::load_sys_func('iconv');
			$in_charset = strtoupper($in_charset);
			$out_charset = strtoupper($out_charset);
			if ($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312')) {
				return utf8_to_gbk($str);
			}
			if (($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8') {
				return gbk_to_utf8($str);
			}
			return $str;
		}
	}
}
/**
 * 格式化金额
 *
 * @param int $money
 * @param int $len
 * @param string $sign
 * @return string
 */
if (!function_exists('format_money')) {
	function format_money($money, $len=2, $sign='￥'){
		if($money<0)
		{
			$money = abs($money);
			$sign = $sign.'-';
		}
		if((int)$money===0) return 0;
		$format_money = '';
		$negative = $money > 0 ? '' : '-';
		$int_money = intval(abs($money));
		$len = intval(abs($len));
		$decimal = '';//小数
		if ($len > 0) {
			$decimal = '.'.substr(sprintf('%01.'.$len.'f', $money),-$len);
		}
		$tmp_money = strrev($int_money);
		$strlen = strlen($tmp_money);
		for ($i = 3; $i < $strlen; $i += 3) {
			$format_money .= substr($tmp_money,0,3).',';
			$tmp_money = substr($tmp_money,3);
		}
		$format_money .= $tmp_money;
		$format_money = strrev($format_money);
		return $sign.$negative.$format_money.$decimal;
	}
}
/**
 * 系统安全问题
 *
 * @return data
 */
if (!function_exists('sys_question')) {
	function sys_question()
	{
		return array('你从哪儿来？','你到哪里去？');
	}
}

if ( ! function_exists('create_cache'))
{
	function create_cache($directory,$file,$data,$flags=FILE_USE_INCLUDE_PATH)
	{

		$all_file =  FCPATH.'data'.DIRECTORY_SEPARATOR.$directory;
		if (!file_exists($all_file)) {
				
			@dir_create($all_file);
		}
		if(is_array($data))
		{
			//要写入PHP文件的数组
			$string_start = '<?php'."\n".'$lang= ';
			$string_process = var_export($data, TRUE);
			$string_end = "; \n?>";
			$string = $string_start.$string_process.$string_end;
		}
		else
		{
			$string	=	$data;
		}

		file_put_contents(FCPATH.'data'.DIRECTORY_SEPARATOR.$directory.DIRECTORY_SEPARATOR.$file,$string,$flags);
	}
}

function url_bind_ip($url, $ip=null) {
	$url = parse_url($url);
	if (!isset($url['port']))  $url['port'] = "";
	if (!isset($url['query'])) $url['query'] = "";
	$encoded = "";
	$fp = fsockopen($ip?$ip:$url['host'], $url['port'] ? $url['port'] : 80);
	fputs($fp, sprintf("POST %s%s%s HTTP/1.1\n", $url['path'], $url['query'] ? "?" : "", $url['query']));
	fputs($fp, "Host: $url[host]\n");
	fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
	fputs($fp, "Content-length: " . strlen($encoded) . "\n");
	fputs($fp, "Connection: close\n\n");
	fputs($fp, "$encoded\n");
	$line = fgets($fp,1024);
	fclose($fp);
	return true;
}

function L($key)
{
	return isset($GLOBALS['lang'][trim($key)])?$GLOBALS['lang'][trim($key)]:0;
}

function C($val,$key)
{
	return isset($GLOBALS[trim($val)][trim($key)])?$GLOBALS[trim($val)][trim($key)]:0;
}

if ( ! function_exists('sys_log'))
{
	/**
	 * 系统操作日志吸入
	 * @param string $actionType 操作类型
	 * @param string $actionDesc 操作描述
	 * @param string $status 操作状态 默认1 成功 0则为失败
	 */
	function sys_log($actionType,$actionDesc,$status=1)
	{
		$CI = & get_instance();
		$CI->load->model('Admin_admin_model');
		$user_logs = array(
                   	'adminId'     	=> $CI->session->userdata('admin_id'),
                   	'actionType'	=> $actionType,
					'actionTime'	  	=> time(),
					'actionIp'	  	=> ip(),
					'actionDesc'	=> $actionDesc,
					'status'	=> $status
		);

		return $CI->Admin_admin_model->insert_userlog($user_logs);
	}
}
if ( ! function_exists('get_vipname_byid'))
{
	function get_vipname_byid($vipid)
	{
		$CI = & get_instance();
		$CI->load->model('User_levels_model');
		$vip_arr = $CI->User_levels_model->get_all();
		$vip_temp_arr = array();
		if(!empty($vip_arr))
		{
			foreach ($vip_arr as $v)
			{
				$vip_temp_arr[$v['id']] = $v['leve_name'];
			}
			return isset($vip_temp_arr[$vipid])?$vip_temp_arr[$vipid]:'NULL';
		}
		else
		{
			return 'NULL';
		}
	}
}
if ( ! function_exists('get_user_acount_status'))
{
	function get_user_acount_status($val)
	{
		$acount_status = array('0'=>L('need_review'),'1'=>L('have_checked'),'2'=>L('disabled'));
		return isset($acount_status[$val])?$acount_status[$val]:'NULL';
	}
}
if ( ! function_exists('get_user_account_type'))
{
	function get_user_account_type($val)
	{
		$account_type = array('0'=>L('the_test'),'1'=>L('formal'));
		return isset($account_type[$val])?$account_type[$val]:'NULL';
	}
}
if ( ! function_exists('get_user_bonus_account'))
{
	function get_user_bonus_account($val)
	{
		$bonus_account = array('0'=>L('in_closed'),'1'=>L('in_open'));
		return isset($bonus_account[$val])?$bonus_account[$val]:'NULL';
	}
}
if ( ! function_exists('get_leve_status'))
{
	function get_leve_status($val)
	{
		$leve_status = array('0'=>L('disabled'),'1'=>L('enable'));
		return isset($leve_status[$val])?$leve_status[$val]:'NULL';
	}
}
if ( ! function_exists('get_year'))
{
	function get_year()
	{
		$birth_year=array();
		for($i=1960;$i<=2099;$i++){
			array_push($birth_year,$i);
		}
		return $birth_year;
	}
}

if ( ! function_exists('get_month'))
{
	function get_month()
	{
		$birth_month=array();
		for($i=1;$i<=12;$i++){
			array_push($birth_month,$i);
		}
		return $birth_month;
	}
}

if ( ! function_exists('get_day'))
{
	function get_day()
	{
		$birth_day=array();
		for($i=1;$i<=31;$i++){
			array_push($birth_day,$i);
		}
		return $birth_day;
	}
}

